<template>
	<div class="container">
		<SearchForm
			@reset="reset"
			@search="search"
			ref="search"
			labelWidth="100px">
			<el-form-item label="应付类型:">
				<el-select
					v-model="queryParams.paymentType"
					placeholder="请选择应付类型"
					clearable>
					<el-option
						v-for="item in dict.type.yf_type"
						:key="item.value"
						:label="item.label"
						:value="item.value"></el-option>
				</el-select>
			</el-form-item>
			<!-- <el-form-item label="费用类型："> -->
			<!-- <el-select -->
			<!-- v-model="queryParams.paymentAmountType" -->
			<!-- placeholder="请选择" -->
			<!-- clearable -->
			<!-- > -->
			<!-- <el-option -->
			<!-- v-for="item in paymentAmountTypeList" -->
			<!-- :key="item.value" -->
			<!-- :label="item.label" -->
			<!-- :value="item.value" -->
			<!-- > -->
			<!-- </el-option> -->
			<!-- </el-select> -->
			<!-- </el-form-item> -->
			<el-form-item label="申请人:">
				<el-input
					clearable
					v-model="queryParams.applyUserName"
					placeholder="请输入申请人"></el-input>
			</el-form-item>
			<el-form-item label="应付单号:">
				<el-input
					clearable
					v-model="queryParams.paymentCode"
					placeholder="请输入应付单号"></el-input>
			</el-form-item>
			<el-form-item label="OA单号:">
				<el-input
					clearable
					v-model="queryParams.oaDataId"
					placeholder="请输入OA单号"></el-input>
			</el-form-item>
			<el-form-item label="单据号:">
				<el-input
					clearable
					v-model="queryParams.documentNo"
					placeholder="请输入单据号"></el-input>
			</el-form-item>
			<el-form-item label="业务单号:">
				<el-input
					clearable
					v-model="queryParams.businessCode"
					placeholder="请输入业务单号"></el-input>
			</el-form-item>

			<el-form-item label="应付状态:">
				<el-select
					v-model="queryParams.paymentStatus"
					placeholder="请选择应付状态"
					clearable>
					<el-option
						v-for="item in paymentStatusList"
						:key="item.value"
						:label="item.label"
						:value="item.value"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="供应商名称:">
				<el-input
					clearable
					v-model="queryParams.payeeName"
					placeholder="请输入供应商名称"></el-input>
			</el-form-item>
			<el-form-item label="公司:">
				<el-select
					v-model="queryParams.deptNames"
					placeholder="请选择公司"
					filterable
					multiple
					collapse-tags
					clearable>
					<el-option
						v-for="item in companyList"
						:key="item.deptId"
						:label="item.deptName"
						:value="item.deptId"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="申请时间:">
				<el-date-picker
					v-model="queryParams.applyTime"
					type="month"
					value-format="yyyy-MM-dd"
					placeholder="请选择申请时间"></el-date-picker>
			</el-form-item>
		</SearchForm>

		<div class="tableBox">
			<div class="card-wrap card-padding">
				<div class="table-title-wrap justify-end">
					<el-button
						type=""
						icon="el-icon-upload2"
						size="mini"
						@click="exportFile"
						v-hasPermi="['finance:manage:payment:list:export']">
						导出
					</el-button>
				</div>
				<table-page
					:loading="loading"
					:dataList="dataList"
					:total="total"
					:page.sync="queryParams.pageNum"
					:limit.sync="queryParams.pageSize"
					:border="true"
					@setSizeCurrent="getList">
					<!-- 操作插槽 -->
					<template slot="tableColAc">
						<el-table-column
							label="操作"
							align="center"
							width="120">
							<template slot-scope="scope">
								<div class="handle">
									<el-button
										size="mini"
										type="text"
										@click="viewDetail(scope.row)"
										v-hasPermi="[
											'finance:manage:payment:list:look',
										]">
										查看
									</el-button>
									<el-button
										v-if="scope.row.paymentStatus == 1"
										size="mini"
										type="text"
										@click="pay(scope.row)">
										付款
									</el-button>
									<!-- v-hasPermi="['demo:demo:remove']" -->
								</div>
							</template>
						</el-table-column>
						<el-table-column
							label="应付单号"
							align="center"
							prop="paymentCode"
							width="190">
							<template slot-scope="scope">
								{{ scope.row.paymentCode }}
							</template>
						</el-table-column>
						<el-table-column
							label="应付状态"
							align="center"
							prop="seriesName"
							show-overflow-tooltip>
							<template slot-scope="scope">
								<div v-if="scope.row.paymentStatusStr">
									<span>
										{{ scope.row.paymentStatusStr }}
									</span>
								</div>
								<div v-else>-</div>
							</template>
						</el-table-column>
						<el-table-column
							label="应付类型"
							align="center"
							min-width="135">
							<template slot-scope="scope">
								<dict-tag
									:options="dict.type.yf_type"
									:value="scope.row.paymentType" />
							</template>
						</el-table-column>

						<el-table-column
							label="业务单号"
							align="center"
							width="250">
							<template slot-scope="scope">
								<!-- {{ scope.row.businessCode }} -->
								<el-link
									type="primary"
									@click="toDetail(scope.row)"
									v-if="notEmpty(scope.row.businessCode)">
									{{ scope.row.businessCode }}
								</el-link>

								<span v-if="Empty(scope.row.businessCode)">
									-
								</span>
							</template>
						</el-table-column>
						<el-table-column
							label="OA单号"
							align="center"
							width="250">
							<template slot-scope="scope">
								{{ scope.row.oaDataId || '-' }}
							</template>
						</el-table-column>
						<el-table-column
							label="单据号"
							align="center"
							width="250">
							<template slot-scope="scope">
								{{ scope.row.documentNo || '-' }}
							</template>
						</el-table-column>
						<el-table-column
							label="供应商名称"
							align="center"
							show-overflow-tooltip
							width="150">
							<template slot-scope="scope">
								{{ scope.row.payeeName }}
							</template>
						</el-table-column>
						<el-table-column label="应付金额" align="center">
							<template slot-scope="scope">
								{{ format_thousand(scope.row.paymentAmount) }}
							</template>
						</el-table-column>

						<el-table-column label="已付金额" align="center">
							<template slot-scope="scope">
								{{ format_thousand(scope.row.prepaidAmount) }}
							</template>
						</el-table-column>
						<el-table-column
							label="收款人"
							align="center"
							min-width="150"
							show-overflow-tooltip>
							<template slot-scope="scope">
								{{ scope.row.payeeName }}
							</template>
						</el-table-column>

						<el-table-column
							label="收款人类型"
							align="center"
							min-width="100">
							<template slot-scope="scope">
								{{ scope.row.payeeTypeStr }}
							</template>
						</el-table-column>
						<el-table-column
							label="收款账户"
							align="center"
							min-width="150"
							show-overflow-tooltip>
							<template slot-scope="scope">
								{{ scope.row.payeeName }}
							</template>
						</el-table-column>
						<el-table-column
							label="收款账号"
							align="center"
							min-width="250">
							<template slot-scope="scope">
								{{ scope.row.payeeAccount }}
							</template>
						</el-table-column>
						<el-table-column
							label="申请人"
							align="center"
							prop="applyUserName"
							show-overflow-tooltip />
						<el-table-column
							label="所属组织"
							align="center"
							prop="deptName"
							show-overflow-tooltip />
						<el-table-column
							label="申请时间"
							align="center"
							prop="applyTime"
							show-overflow-tooltip>
							<template slot-scope="scope">
								<div>
									{{ scope.row.applyTime | formatTime(0) }}
								</div>
							</template>
						</el-table-column>
					</template>
				</table-page>
			</div>
		</div>
		<el-dialog
			title="付款"
			@opened="opend"
			:visible.sync="dialog.pay.show"
			width="500px"
			@closed="closed">
			<div class="dialog-pay_box">
				<el-form
					:model="dialog.pay.data"
					ref="formPay"
					label-width="110px"
					:inline="false">
					<el-form-item label="应付单号:">
						{{ dialog.pay.data.paymentCode }}
					</el-form-item>
					<el-form-item label="应付类型:">
						<dict-tag
							:options="dict.type.yf_type"
							:value="dialog.pay.data.paymentType" />
					</el-form-item>
					<el-form-item
						label="费用所属公司:"
						prop="costCompanyId"
						:rules="[
							{
								required: true,
								message: '费用所属公司不能为空',
								trigger: 'change',
							},
						]">
						<el-select
							v-model="dialog.pay.data.costCompanyId"
							placeholder=""
							clearable
							size="mini"
							@change="changeCompany"
							filterable>
							<el-option
								v-for="item in companyList"
								:key="item.deptId"
								:label="item.deptName"
								:value="item.deptId"></el-option>
						</el-select>
					</el-form-item>
				</el-form>
			</div>
			<span slot="footer">
				<el-button @click="dialog.pay.show = false">取消</el-button>
				<el-button type="primary" @click="submitPay">付款</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import * as app from '@/api/app.js';
	import * as apis from '@/api/finance/manage/payment/api.js';
	import * as jump from '@/api/finance/manage/collect/api.js';
	import { Params } from '@/api/finance/reimburs/list/api.js';
	import TooltipDiv from '@/views/quota/forecast/chunk/tooltipDiv';
	export default {
		name: 'Payment',
		components: { TooltipDiv },
		data() {
			return {
				value: '',
				options: '',
				total: 0,
				loading: true,
				queryParams: {
					paymentType: '',
					paymentAmountType: '',
					applyUserName: '',
					paymentCode: '',
					pageNum: 1,
					pageSize: 10,
				},
				dataList: [],
				companyList: [],
				paymentStatusList: [
					{
						label: '未支付',
						value: '1',
					},
					{
						label: '已付款',
						value: '2',
					},
					{
						label: '已推送',
						value: '3',
					},
				],
				dialog: {
					pay: {
						show: false,
						data: {},
					},
				},
			};
		},
		dicts: ['payment_type', 'expense_type', 'yf_type'],
		computed: {
			paymentTypeList() {
				return this?.dict?.type?.payment_type ?? [];
			},
			paymentAmountTypeList() {
				return this?.dict?.type?.expense_type ?? [];
			},
		},
		created() {
			this.getList();
			this.getDeptList(2);
		},
		activated() {
			this.getList();
		},
		methods: {
			getoutChangeRentParam(orderCode) {
				if (this.Empty(orderCode)) return Promise.reject();
				return new Promise((resolve, reject) => {
					jump.outChangeRentParam({ code: orderCode }).then(res => {
						if (res.code == 200 && this.notEmpty(res.data)) {
							resolve(res.data);
						} else {
							reject(res);
						}
					});
				});
			},
			getDeptList(deptType) {
				let params = {
					deptType,
				};
				app.DeptListNoPermission(params).then(res => {
					if (res.code == 200) {
						res?.data?.map(item => {
							item.deptId = item.deptId;
						});
						switch (deptType) {
							case 2:
								this.companyList = res?.data ?? [];
								break;
						}
					}
				});
			},
			async toDetail(row) {
				try {
					this.$modal.loading('正在跳转中，请稍后...');
					let {
						businessCode,
						paymentType,
						businessId,
						purchaseOrderId,
						flowId,
						purchaseSource,
					} = row;
					if (this.Empty(paymentType)) return;
					let route = {};
					switch (paymentType?.toString()) {
						// 报销
						case '1':
							if (!businessId) break;
							route = {
								path: '/finance/previewReimburs',
								name: 'PreviewReimburs',
								query: {
									id: businessId,
									type: 'preview',
									flowId,
								},
							};
							break;
						// 车辆采购尾款应付款
						case '2':
							if (!purchaseOrderId) break;
							if (purchaseSource == 2) {
								route = {
									name: 'OrderPurchase',
									query: {
										purchaseOrderId,
										type: 'detail',
										pageType: '订单采购详情',
									},
								};
							} else {
								route = {
									name: 'PurchaseAdd',
									query: {
										purchaseOrderId,
										type: 'detail',
										pageType: '采购详情',
									},
								};
							}
							break;
						// 车辆采购定金应付款
						case '3':
							if (!purchaseOrderId) break;
							if (purchaseSource == 2) {
								route = {
									name: 'OrderPurchase',
									query: {
										purchaseOrderId,
										type: 'detail',
										pageType: '订单采购详情',
									},
								};
							} else {
								route = {
									name: 'PurchaseAdd',
									query: {
										purchaseOrderId,
										type: 'detail',
										pageType: '采购详情',
									},
								};
							}
							break;
						// 车辆外部转租赁首付款
						case '4':
							if (!businessCode) break;
							var params = await this.getoutChangeRentParam(
								businessCode,
							);
							route = {
								name: 'SubleaseView',
								query: {
									type: 'view',
									id: params.id,
								},
							};
							break;
						// 车辆外部转租赁保证金
						case '5':
							if (!businessCode) break;
							var params = await this.getoutChangeRentParam(
								businessCode,
							);
							route = {
								name: 'SubleaseView',
								query: {
									type: 'view',
									id: params.id,
								},
							};
							break;
						// 新车投保
						case '6':
							if (/^BX.*/g.test(businessCode)) {
								let params = await this.getParams(businessCode);
								// 单推
								route = {
									path: '/cwgd/newCarInsuranceDetails',
									name: 'NewCarInsuranceDetails',
									query: {
										id: params.id,
										carId: params.carId,
										channels: params.insuranceChannels,
										businessDataId: params.businessDataId,
										flowId: params?.flowId || null,
										type: 'view',
									},
								};
							}
							if (/^PCHBX.*/g.test(businessCode)) {
								if (!flowId) {
									this.$message.error('未查找到相关流程！');
									break;
								}
								// 批量
								route = {
									path: '/workflow/examine/details',
									name: 'Details',
									query: {
										processId: flowId,
										flag: '1',
										status: 'readonly',
									},
								};
							}

							break;
						// 保险变更
						case '7':
							if (!businessId) break;
							route = {
								name: 'InsureManageDetails',
								query: {
									id: businessId,
								},
							};
							break;
						// 保险理赔
						case '8':
							if (!businessId) break;
							route = {
								name: 'SettlementDetails',
								query: {
									id: businessId,
									type: 'view',
								},
							};
							break;
						// 车辆采购全款应付款;
						case '9':
							if (!purchaseOrderId) break;
							if (purchaseSource == 2) {
								route = {
									name: 'OrderPurchase',
									query: {
										purchaseOrderId,
										type: 'detail',
										pageType: '订单采购详情',
									},
								};
							} else {
								route = {
									name: 'PurchaseAdd',
									query: {
										purchaseOrderId,
										type: 'detail',
										pageType: '采购详情',
									},
								};
							}
							break;
						// GPS续费
						case '10':
							var params = await this.getParams(businessCode);
							route = {
								name: 'GPSRenewal',
								query: {
									// data: row,
									carIds: params.carId,
									workOrderType: params.workOrderType,
									type: 'disabled',
									pageType: 'GPS续费工单详情',
								},
							};
							break;
						// GPS维修
						case '11':
							var params = await this.getParams(businessCode);
							route = {
								name: 'GPSFix',
								query: {
									// data: row,
									carIds: params.carId,
									workOrderType: params.workOrderType,
									type: 'disabled',
									pageType: 'GPS维修工单详情',
								},
							};
							break;
						// GPS拆除
						case '12':
							var params = await this.getParams(businessCode);
							route = {
								name: 'GPSRemove',
								query: {
									// data: row,
									carIds: params.carId,
									workOrderType: params.workOrderType,
									type: 'disabled',
									pageType: 'GPS拆除工单详情',
								},
							};
							break;
						// 处置金应付
						case '13':
							route = {};
							break;
					}
					this.$modal.closeLoading();
					if (this.notEmpty(route)) {
						this._toPage(route);
					}
				} catch (error) {
					this.$message.error('未查找到相关订单信息！');
					this.$modal.closeLoading();
				}
			},
			getParams(businessCode) {
				return new Promise((resolve, reject) => {
					Params(businessCode)
						.then(res => {
							if (res.code == 200) {
								resolve(res.data);
							} else {
								throw new Error(res.msg);
							}
						})
						.catch(err => {
							reject(err);
						});
				});
			},
			exportFile() {
				if (!apis?.exportFile) return;
				let params = this._.cloneDeep(this.queryParams);
				params.deptNames = params?.deptNames?.join(',');
				this.download(
					apis?.exportFile,
					params,
					`应付账款_${new Date().getTime()}.xlsx`,
				);
			},
			search() {
				this.queryParams.pageNum = 1;
				this.getList();
			},
			reset() {
				this.queryParams = {
					pageNum: 1,
					pageSize: 10,
				};
				this.getList();
			},
			getList() {
				this.loading = true;
				let params = this._.cloneDeep(this.queryParams);
				params.deptNames = params?.deptNames?.join(',');
				apis?.List?.(params)
					.then(res => {
						this.dataList = res.rows ?? [];
						this.total = res.total ?? 0;
					})
					.catch(err => {
						console.log(err);
					})
					.finally(() => {
						this.loading = false;
					});
			},
			viewDetail(data) {
				this._toPage({
					name: 'PaymentDetail',
					query: {
						paymentId: data.paymentId,
					},
				});
			},
			pay(row) {
				this.dialog.pay.data = { ...row };
				this.dialog.pay.show = true;
				// this.$confirm('是否支付此条账单?', '提示', {
				// 	confirmButtonText: '确定',
				// 	cancelButtonText: '取消',
				// 	type: 'warning',
				// }).then(() => {
				// 	apis?.Pay?.({ paymentId: row.paymentId }).then(res => {
				// 		if (res.code == 200) {
				// 			this.$message({
				// 				message: '推送成功！',
				// 				type: 'success',
				// 			});
				// 			this.getList();
				// 		}
				// 	});
				// });
			},
			changeCompany() {
				let item = this.companyList.find(
					e => e.deptId == this.dialog.pay.data.costCompanyId,
				);
				if (item) {
					this.dialog.pay.data.costCompanyName = item.deptName;
				}
			},
			opend() {
				this.$refs.formPay.clearValidate();
			},
			closed() {
				this.dialog.pay.data = {};
			},
			submitPay() {
				this.$refs.formPay.validate(valid => {
					if (!valid) return;
					let params = {
						paymentId: this.dialog.pay.data.paymentId,
						costCompanyId: this.dialog.pay.data.costCompanyId,
						costCompanyName: this.dialog.pay.data.costCompanyName,
					};
					this.$modal.loading('正在提交数据，请稍后...');
					apis.Pay(params)
						.then(res => {
							if (res.code == 200) {
								this.$message({
									type: 'success',
									message: '付款成功',
								});
								this.dialog.pay.show = false;
								this.getList();
							}
						})
						.finally(() => {
							this.$modal.closeLoading();
						});
				});
			},
		},
	};
</script>

<style scoped lang="scss">
	.container {
		padding: 15px;
		box-sizing: border-box;
	}
	.searchForm {
		padding: 15px;
		display: grid;
		gap: 10px 15px;
		grid-template-columns: repeat(4, minmax(0, 1fr));
		background-color: #fff;
		.item {
			display: flex;
			align-items: center;
			.label {
				width: 80px;
				font-size: 14px;
				margin-right: 15px;
				vertical-align: middle;
				color: #606266;
				font-weight: 700;
			}
			.content {
				flex: 1;
			}
		}
	}
	::v-deep .el-form-item {
		.el-form-item__label {
			white-space: nowrap;
		}
	}
	.tableBox {
		margin-top: 20px;
		background-color: #fff;
	}
	.searchbtns {
		padding: 20px 15px;
		background-color: #fff;
		display: flex;
		justify-content: space-between;
	}
	.handle {
		display: flex;
		justify-content: space-around;
		::v-deep .el-button + .el-button {
			margin: 0;
		}
	}
</style>
